<template>
  <div>
    <ColPage auto-content-height v-bind="props" class="!p-0">
      <template #left="{ isCollapsed, expand }">
        <div v-if="isCollapsed" @click="expand">
          <el-tooltip content="点击展开左侧">
            <el-button shape="circle" type="primary">
              <template #icon>
                <IconifyIcon class="text-2xl" icon="bi:arrow-right" />
              </template>
            </el-button>
          </el-tooltip>
        </div>
        <div
          v-else
          :style="{ minWidth: '200px', height: '100%' }"
          class="border-border bg-card mr-2 rounded-[var(--radius)] border p-2"
        >
          <LeftCard @search-department="searchUserHandle" />
        </div>
      </template>
      <el-card class="ml-2">
        <BaseForm />
      </el-card>
      <el-card class="ml-2 mt-4">
        <FosoTable
          :tool-bar-button-text="$t('sys.position.addPosition')"
          table-title="用户管理"
          table-titlehelp="用户管理帮助"
          @add="openDrawerHandle('add', $event)"
        >
          <!-- 状态列 -->
          <template #status="{ row }">
            <StatusColumn :request-api="updateUser" :row="row" />
          </template>
          <!-- 操作列 -->
          <template #action="{ row }">
            <OperationColumn
              :row="row"
              @delete="DeleteHandle(row)"
              @edit="openDrawerHandle('edit', $event)"
            >
              <template #middleOperationButton="">
                <el-button :icon="SwitchButton" link type="primary" />
              </template>
            </OperationColumn>
          </template>
        </FosoTable>
      </el-card>
    </ColPage>
    <!-- 弹窗框 -->
    <Drawer class="w-[40%]" @refresh="reloadTable" />
  </div>
</template>
<script lang="ts" setup>
import type { UserInfo } from '#/api/sys/model/userModel';

import { reactive } from 'vue';

import { ColPage, useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { $t } from '@vben/locales';

import { SwitchButton } from '@element-plus/icons-vue';

import { useVbenForm } from '#/adapter/form';
import { deleteUser, getUserList, updateUser } from '#/api/sys/user';
import { OperationColumn } from '#/components/FosoTablePro/index';
import { useFosoTable } from '#/components/FosoTablePro/use-foso-config';
import { useFosoTableConfig } from '#/components/FosoTablePro/use-foso-table';

import ExtraDrawer from './components/drawer.vue';
import LeftCard from './components/LeftCard.vue';

const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});

const [BaseForm] = useVbenForm({
  // 默认展开
  collapsed: true,
  layout: 'horizontal',
  // 提交函数
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  handleSubmit: searchHandle,
  wrapperClass: 'grid-cols-1 md:grid-cols-3',
  schema: [
    {
      component: 'Input',
      fieldName: 'username',
      label: $t('sys.login.username'),
    },
    {
      component: 'Input',
      fieldName: 'nickname',
      label: $t('sys.user.nickname'),
    },
    {
      component: 'Input',
      fieldName: 'roleIds',
      label: $t('sys.role.roleTitle'),
    },
    {
      component: 'Input',
      fieldName: 'mobile',
      label: $t('sys.login.mobile'),
    },
    {
      component: 'Input',
      fieldName: 'email',
      label: $t('sys.login.email'),
    },
  ],
});

const props = reactive({
  leftCollapsedWidth: 5,
  leftCollapsible: true,
  leftMaxWidth: 30,
  leftMinWidth: 20,
  leftWidth: 20,
  resizable: true,
  rightWidth: 70,
  splitHandle: false,
  splitLine: false,
});

// 使用 useFosoTable hook 生成配置
const { gridOptions } = useFosoTableConfig({
  columns: [
    {
      type: 'checkbox',
      width: 120,
    },
    { field: 'username', title: $t('sys.login.username'), treeNode: true },
    { field: 'nickname', title: $t('sys.user.nickname') },
    {
      field: 'email',
      sortable: true,
      title: $t('sys.login.email'),
    },
    {
      field: 'updatedAt',
      title: $t('sys.menu.createTime'),
      formatter: ['formatDate', 'yyyy-MM-dd'],
    },
    {
      field: 'status',
      title: $t('sys.menu.status'),
      slots: {
        default: 'status',
      },
    },
    {
      field: 'status66',
      title: $t('sys.menu.operation'),
      width: 300,
      slots: { default: 'action' },
    },
  ],
  height: '1000px',
  requestApi: getUserList,
});

const { FosoTable, FosoTableApi } = useFosoTable(gridOptions);

/**
 * @author Buke
 * @description 打开弹窗
 * @param {string} type - 操作类型，'edit' 表示编辑，'add' 表示新增。
 * @param {UserInfo} row - 要编辑的行数据对象，包含字典相关信息。
 * @returns {void}
 */
const openDrawerHandle = (type: string, row?: UserInfo): void => {
  if (type === 'edit') {
    drawerApi.setState({ title: $t('sys.role.editRole') });
    drawerApi.setData({ type: 'editData', id: row?.id as number });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
  if (type === 'add') {
    drawerApi.setState({ title: $t('sys.user.addUser') });
    drawerApi.setData({ type: 'addData' });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
};

/**
 * @author Buke
 * @description 搜索用户
 * @param {any} params - 搜索参数。
 * @returns {void}
 */
const searchUserHandle = async (params: any): Promise<void> => {
  FosoTableApi.commitProxy('reload', { departmentId: params.id });
};

/**
 * @author Buke
 * @description 删除字典
 * @param {any} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: any): Promise<void> {
  try {
    await deleteUser(row.id as number);
    ElMessage.success('删除成功');
    FosoTableApi.commitProxy('reload');
  } catch {
    ElMessage.error('删除失败');
  }
}

const reloadTable = () => {
  FosoTableApi.commitProxy('reload');
  drawerApi.close();
};

function searchHandle(params: any) {
  FosoTableApi.commitProxy('reload', params);
}
</script>
